﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QDSpider
{
    public static class DictionalHelper
    {
        private const string FileName = "user.config";
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Save(string key, string value)
        {
            var absolutePath = AppDomain.CurrentDomain.BaseDirectory + FileName;
            using (var stream = new FileStream(absolutePath, FileMode.OpenOrCreate))
            {
                var newline = Encoding.UTF8.GetBytes($"{key}={value}");
                stream.Write(newline, 0, newline.Length);
                stream.Flush();
            }
        }



        public static KeyValuePair<string, string> ReadFirsKeyValuePair()
        {
            var absolutePath = AppDomain.CurrentDomain.BaseDirectory + FileName;
            using (var stream = new FileStream(absolutePath, FileMode.OpenOrCreate))
            {
                var content = new byte[stream.Length];
                stream.Read(content, 0, (int)stream.Length);
                var s = Encoding.UTF8.GetString(content);
                if (string.IsNullOrEmpty(s))
                    return default(KeyValuePair<string, string>);
                var v = s.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                return v.Length != 2 ?default(KeyValuePair<string, string>) :new KeyValuePair<string, string>(v[0], v[1]);
            }
        }


    }
}
